import { defineStore } from 'pinia'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    getUser: (state) => state.user
  },
  
  actions: {
    async login(username, password) {
      try {
        const response = await axios.post('http://localhost:8000/token', {
          username,
          password
        })
        this.token = response.data.access_token
        localStorage.setItem('token', this.token)
        await this.fetchUser()
        return true
      } catch (error) {
        console.error('Login error:', error)
        throw error
      }
    },

    async register(username, email, password) {
      try {
        await axios.post('http://localhost:8000/register', {
          username,
          email,
          password
        })
        return true
      } catch (error) {
        console.error('Registration error:', error)
        throw error
      }
    },

    async fetchUser() {
      try {
        const response = await axios.get('http://localhost:8000/users/me', {
          headers: {
            Authorization: `Bearer ${this.token}`
          }
        })
        this.user = response.data
      } catch (error) {
        console.error('Fetch user error:', error)
        throw error
      }
    },

    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
    }
  }
}) 